<template>
    <div>
        <!-- :inline="true" 表单中控件排列从左到右
         :model="searchForm" 表单控件绑定的对象
        -->
        <el-form ref="searchForm" :model="searchForm" :inline="true">
            <el-form-item>
                <el-input v-model="searchForm.businessName" placeholder="输入搜索的分类名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="getBusinessList()">搜索</el-button>
                <el-button type="primary" @click="dialogFormVisible = true">新建</el-button>
                <el-popconfirm title="确认要删除这些记录吗？" @confirm="delHandler(null)">
                    <el-button type="danger" :disabled="delBtnStu" slot="reference">批量删除</el-button>
                </el-popconfirm>
            </el-form-item>
        </el-form>


        <!-- 分类表格 -->
        <el-table :data="tableData" border style="width:100%;margin-bottom: 20px;" :cel1-style="{ padding: '2px' }"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="businessName" label="分类名称" width="200"></el-table-column>
            <!-- 如果读取字段数据就是文字，直接显示在表格，那么就使用 prop="字段属性名"-->
            <el-table-column label="商家图片" width="100">
                <!--数据不是直接显示在页面，而是通过其它模版页面显示 -->
                <template slot-scope="scope">
                    <!-- scope表示表格当前行的数据。scope.row就是表格这一行记录(一个分类对象)-->
                    <el-image style="width:40px; height:40px" :src="scope.row.businessImg" />
                </template>
            </el-table-column>
            <el-table-column prop="businessAddress" label="商家地址" width="250"></el-table-column>
            <el-table-column prop="businessExplain" label="描述" width="150"></el-table-column>
            <el-table-column prop="starPrice" label="起送费" width="150"></el-table-column>
            <el-table-column prop="deliveryPrice" label="配送价格" width="150"></el-table-column>
            <el-table-column prop="created" label="创建时间" width="200"></el-table-column>
            <el-table-column prop="updated" label="更新时间" width="200"></el-table-column>
            <el-table-column prop="statu" label="状态" width="150">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.statu == 1" type="success" size="mini">正常</el-tag>
                    <el-tag v-else-if="scope.row.statu == 0" type="danger" size="mini">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right"  label="操作" width="260px">
                <template slot-scope="scope">
                    <el-button type="text" @click="editBusiness(scope.row.businessId)">编辑</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-popconfirm title="确认要删除该记录吗？" @confirm="delHandler(scope.row.businessId)">
                        <el-button type="text" slot="reference">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!--分页组件
        handleSizeChange()方法，切换一页显示的记录数交互方法。
        -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current"
            :page-sizes="[5, 10, 15, 20]" :page-size="size" layout="total,sizes,prev, pager, next,jumper"
            :total="total">
        </el-pagination>

        <!--新建分类消息框
        :visible.sync对话框是否显示，true显示，false不显示
        -->
        <el-dialog title="分类消息" width="600px" :visible.sync="dialogFormVisible">
            <el-form ref="categoryForm" :model="categoryForm">
                <el-form-item label="分类名称">
                    <el-input v-model="businessForm.businessName"></el-input>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 新建商家消息框
        :visible.sync对话框是否显示，true显示，false不显示
        -->
        <el-dialog title="商家信息" width="600px" :visible.sync="dialogFormVisible" @close="closeDialog">
            <el-form :model="businessForm" ref="businessForm" :rules="businessRules">
                <!--
                action的属性值，必须添加/sys前缀，目的是实现跨域
                :headers="headers" 设置上传图片组件的请求头信息，添加token令牌
                -->
                <el-form-item label="上传图片" label-width="100px">
                    <div style=" border: 1px dashed #000; width:180px; height:180px;">
                        <el-upload class="avatar-uploader" name="file" action="/sys/api/upload" :show-file-list="false"
                            :headers="headers" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="businessForm.businessImg" :src="businessForm.businessImg" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </el-form-item>

                <el-form-item label="分类选择" label-width="100px">
                    <el-select v-model="businessForm.categoryId" placeholder="请选择分类信息">
                        <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName"
                            :value="item.categoryId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商家名称" label-width="100px" prop="businessName">
                    <el-input v-model="businessForm.businessName" style="width:60%"></el-input>
                </el-form-item>
                <el-form-item label="商家地址" label-width="100px" prop="businessAddress">
                    <el-input v-model="businessForm.businessAddress" style="width:80%"></el-input>
                </el-form-item>
                <el-form-item label="商家描述" label-width="100px" prop="businessExplain">
                    <el-input v-model="businessForm.businessExplain" style="width:40%"></el-input>
                </el-form-item>
                <el-form-item label="起送价格" label-width="100px">
                    <!-- precision属性 数值精度
                    step属性 每次增量
                    -->
                    <el-input-number v-model="businessForm.starPrice" :precision="1" :step="0.5" :max="50"
                        :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="配送价格" label-width="100px">
                    <el-input-number v-model="businessForm.deliveryPrice" :precision="1" :step="0.5" :max="30"
                        :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="状态" label-width="100px">
                    <el-radio-group v-model="businessForm.statu">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label-width="100px">
                    <el-button type="primary" @click="submitBusinessForm('businessForm')">保存
                    </el-button>
                    <el-button>重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            dialogFormVisible: false,//新建分类的消息框是否显示 true显示，false不显示
            delBtnStu: true,//批量删除按钮是否可用。true不可用，false可以使用
            //搜索栏的对象
            searchForm: {
                businessName: ''
            },
            //新建分类对象
            businessForm: {
                categoryId: 1,
                businessName: '',
                businessImg: '',
                businessAddress: '',
                businessExplain: '',
                starPrice: 0.0,
                deliveryPrice: 0.0,
                statu: 1,
            },
            tableData: [],//分类信息分页表格数组
            //分页参数
            current: 1,
            size: 5,
            total: 0,
            //商家添加验证规则
            businessRules: {
                businessName: [
                    { required: true, message: '请输入商家的名称', trigger: 'blur' }
                ],
                businessAddress: [
                    { required: true, message: '请输入商家的地址', trigger: 'blur' }
                ],
                businessExplain: [
                    { required: true, message: '请输入商家的描述', trigger: 'blur' }
                ],
            },
            //表格复选框选中数组，存储选中表格中某些行对象
            selection: [],
            headers: {
                token: JSON.parse(localStorage.getItem('TOKEN'))
            }
        }
    },
    created() {
        this.getBusinessList();
        this.getCategoryList();
    },
    methods: {
        //重置businessForm对象的方法
        resetBusinessForm() {
            this.businessForm = {
                categoryId: 1,
                businessName: '',
                businessImg: '', //商家图片
                businessAddress: '',
                businessExplain: '',
                starPrice: 0.0,
                deliveryPrice: 0.0,
                statu: 1,
            }
        },
        //关闭对话框重置businessForm表单对象
        closeDialog() {
            this.resetBusinessForm();
        },
        //编辑商家数据
        editBusiness(businessId) {
            //请求服务器端，通过businessId查询该商家对象，然后将获得商家详细数据 回显到对话框
            let url = "/business/getById/" + businessId;
            this.$axios.get(url).then(response => {
                this.businessForm = response.data.resultdata;
                this.dialogFormVisible = true;
            }).catch(e => {
                console.log(e);
            })
        },
        handleSelectionChange(arr) {//选择表格的复选框触发事件，参数arr就是选中
            this.selection = arr;
            if (this.selection) {
                this.delBtnStu = (this.selection.length == 0)
            }
        },
        delHandler(businessId) { //删除记录的方法
            //请求服务器端，传递需要删除 分类信息id的数组
            var businessIds = []; //删除分类编号数组
            businessId ? businessIds.push(businessId) : this.selection.forEach(business => {
                businessIds.push(business.businessId);
            });
            let url = "/business/delete";
            this.$axios.post(url, businessIds).then(response => {
                this.$message({
                    message: response.data.resultdata,
                    type: "success"
                });
                //重新加载 分类信息表格数据
                this.getBusinessList();
            }).catch(e => {
                console.log(e);
            });
        },
        submitBusinessForm(formName) { //保存商家信息
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$axios.post('/business/' +
                        (this.businessForm.businessId ? 'update' : 'save'), this.businessForm)
                        .then(response => {
                            this.$message({
                                showClose: true,
                                message: response.data.resultdata,
                                type: 'success',
                            });
                            this.getBusinessList(); //录入新的分类数据，重新加载表格数据
                            this.dialogFormVisible = false; //保存成功，录入消息框隐藏
                            this.resetBusinessForm(); //重置businesForm表单对象
                        }).catch(e => { console.log(e); })
                } else {
                    return false;
                }
            });
        },
        beforeAvatarUpload() { //上传之前进行操作
            //对于上传图片有限制：图片格式jpeg 图片大小 10MB
        },
        handleAvatarSuccess(response, file) { //上传图片成功之后的回调。
            //图片上传，获得上传图片的地址（图片数据）进行回显。
            //参数response就是服务器端返回Result对象，不需要像axios对象中的操作response.data这样。
            this.businessForm.businessImg = response.resultdata
        },
        handleCurrentChange(val) {//切换到某一页数据 参数val 就是切换页码
            this.current = val;
            //页码发生变化，重新去请求Table中分页数据
            this.getBusinessList();
        },
        handleSizeChange(val) { //一页显示的记录数切换，参数val 切换一页要显示的数量
            this.size = val
            //一页显示的记录数发生变化，重新去请求Table中分页数据
            this.getBusinessList();
        },
        getCategoryList() { //请求所有的分类信息
            let url = "/category/all";
            this.$axios.get(url).then(response => {
                this.categoryList = response.data.resultdata;
            }).catch(e => {
                console.log(e);
            })
        },
        getBusinessList() { //加载页面上分类数据
            //Vue2中，将axios已经挂载this（vue实例中）
            let url = "/business/list";
            this.$axios.get(url, {
                params: {
                    //搜索的内容
                    businessName: this.searchForm.businessName,
                    current: this.current,
                    size: this.size
                }
            }).then(response => {
                //服务器返回分页对象数据。具体分类数据records属性中。
                this.tableData = response.data.resultdata.records;
                this.current = response.data.resultdata.current;
                this.size = response.data.resultdata.size;
                this.total = response.data.resultdata.total;
            }).catch(e => {
                console.log(e);
            })
        },
    },
}
</script>
<style scoped>
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: 178px;
}
</style>
